<?php
namespace app\home\controller;

use app\common\controller\Home;
use app\common\model\Coupon\Coupon;
use app\common\model\Coupon\Receive;
use think\Request;

class Discount extends Home{
    public function __construct(Request $request)
    {
        $this->noLogin = ['index'];
        parent::__construct($request);
    }
    public function coupon_list(Request $request)
    {
        if($request->isGet())
        {
            return $this->fetch();
        }
        
        $pageNum = $request->param('pageNum')?$request->param('pageNum'):1;
        $pageSize = $request->param('pageSize')?$request->param('pageSize'):5;
        $option = $request->param('option')?$request->param('option'):0;
        switch($option){
            case(0):
                $coupon = Coupon::order('createtime','desc')
                    ->limit(($pageNum-1)*$pageSize,$pageSize)
                    ->select();
                $total = Coupon::count();
                $coupon->each(function($data){
                    if(time()<$data['createtime']){
                        $data['statusTime']=['code'=>1,'msg'=>'未开始'];
                    }else if(time()>$data['endtime']){
                        $data['statusTime']=['code'=>0,'msg'=>'已结束'];
                    }else{
                        $data['statusTime']=['code'=>1,'msg'=>'期间'];
                    }
                    if(Receive::field('id')->where(['busid'=>$this->business['id'],'cid'=>$data['id']])->find()){
                        $data['status']=['code'=>0,'msg'=>'已领取'];
                    }else{
                        $data['status']=['code'=>1,'msg'=>'立即领取'];
                    }
                });
                break;
            case(1):
                $receive = Receive::where(['busid'=>$this->business['id'],'status'=>1])
                    ->order('createtime','desc')
                    ->limit(($pageNum-1)*$pageSize,$pageSize)
                    ->select()->toArray();
                $coupon = [];
                foreach($receive as $r)
                {
                    $coupon[] = $r['coupon'];
                }
                foreach($coupon as $i=>$data){
                    $coupon[$i]['status']=['code'=>0,'msg'=>'已领取'];
                }
                $total = Receive::where(['busid'=>$this->business['id'],'status'=>1])->count();
                break;
            case(2):
                $receive = Receive::where(['busid'=>$this->business['id'],'status'=>0])
                    ->order('createtime','desc')
                    ->limit(($pageNum-1)*$pageSize,$pageSize)
                    ->select()->toArray();
                    $coupon = [];
                    foreach($receive as $r)
                    {
                        $coupon[] = $r['coupon'];
                    }
                    foreach($coupon as $i=>$data){
                        $coupon[$i]['status']=['code'=>0,'msg'=>'已领取'];
                    }
                $total = Receive::where(['busid'=>$this->business['id'],'status'=>0])->count();
                break;
            case(3):
                $coupon = Coupon::where('createtime','>',time())
                    ->order('createtime','desc')
                    ->limit(($pageNum-1)*$pageSize,$pageSize)
                    ->select();
                $coupon->each(function($data){
                    $receive = Receive::where(['busid'=>$this->business['id'],'cid'=>$data['id']])->find();
                    if($receive){
                        $data['statusTime']=['code'=>1,'msg'=>'未开始'];
                        $data['status']=['code'=>0,'msg'=>'已领取'];
                    }else{
                        $data['statusTime']=['code'=>1,'msg'=>'未开始'];
                        $data['status']=['code'=>1,'msg'=>'立即领取'];
                    }
                });
                $total = Coupon::where('createtime','>',time())->count();
                break;
            case(4):
                $coupon = Coupon::where('endtime','<',time())
                    ->order('createtime','desc')
                    ->limit(($pageNum-1)*$pageSize,$pageSize)
                    ->select();
                $coupon->each(function($data){
                    $receive = Receive::where(['busid'=>$this->business['id'],'cid'=>$data['id']])->find();
                    if($receive){
                        $data['statusTime']=['code'=>0,'msg'=>'已结束'];
                        $data['status']=['code'=>0,'msg'=>'已领取'];
                    }else{
                        $data['statusTime']=['code'=>0,'msg'=>'已结束'];
                        $data['status']=['code'=>1,'msg'=>'立即领取'];
                    }
                });
                $total = Coupon::where('endtime','<',time())->count();
                break;
        }
        
        $page = [];
        $page['curPageData'] = $coupon;
        $page['totalPage'] = ceil($total/$pageSize);
        return $page;
    }
    public function getCoupon(Request $request)
    {
        $cid = trim($request->post('id'));
        $status = ['code'=>0,'msg'=>'领取失败'];
        if(!isset($cid))return $status;
        $coupon = Coupon::where('id',$cid)->find();
        if(!$coupon){
            $status['msg'] = '优惠券不存在';
        }else if(time()>$coupon['endtime']){
            $status['msg'] = '活动已结束';
        }else if(Receive::field('id')->where(['busid'=>$this->business['id'],'cid'=>$cid])->find()){
            $status['msg'] = '已领取';
        }else if($coupon['total']==0){
            $status['msg'] = '优惠券已领取完';
        }else{
            $data = [
                'cid'=>$cid,
                'busid'=>$this->business['id'],
                'status'=>'1'
            ];
            Coupon::startTrans();
            Receive::startTrans();
            try{
                $result = Receive::create($data);
                $coupon['total'] -= 1;
                $coupon->isUpdate(true)->save();
                Coupon::commit();
                Receive::commit();
            } catch (\Exception $e) {
                $result = false;
                Coupon::rollback();
                Receive::rollback();
            }
            if($result){
                $status['code'] = 1;
                $status['msg'] = '领取成功';
                if(time()<$coupon['createtime']){
                    $status['msg'] .= '活动未开始,';
                }
            }else{
                $status['msg'] = '领取失败';
            }
        }
        return $status;
    }
    public function coupon_info(Request $request)
    {
        $id = $request->param('id')?trim($request->param('id')):null;
        $coupon = Coupon::where('id',$id)->find();
        if(time()<$coupon['createtime']){
            $coupon['statusTime']=['code'=>1,'msg'=>'未开始'];
        }else if(time()>$coupon['endtime']){
            $coupon['statusTime']=['code'=>0,'msg'=>'已结束'];
        }else{
            $coupon['statusTime']=['code'=>1,'msg'=>'期间'];
        }
        if(Receive::field('id')->where(['busid'=>$this->business['id'],'cid'=>$coupon['id']])->find()){
            $coupon['status']=['code'=>0,'msg'=>'已领取'];
        }else{
            $coupon['status']=['code'=>1,'msg'=>'立即领取'];
        }
        $this->assign('coupon',$coupon);

        $receives = Receive::where(['cid'=>$coupon['id']])->order('createtime','desc')->limit(10)->select();
        $this->assign('receives',$receives);
        return $this->fetch();
    }
    public function coupon_bus(Request $request)
    {
        if($request->isGet()){
            return $this->fetch();
        }
        $option = $request->post('option')?trim($request->post('option')):0;
        $receives = Receive::where('busid',$this->business['id'])->select()->toArray();
        $coupons = [];
        foreach($receives as $i=>$receive){
            $coupons[$i] = $receive['coupon'];
            $coupons[$i]['collectionTime'] = $receive['createDate'];
            if($receive['status']==1){
                $coupons[$i]['statusUseable'] = ['code'=>1,'msg'=>'未使用'];
            }else{
                $coupons[$i]['statusUseable'] = ['code'=>0,'msg'=>'已使用'];
            }
            if(time()<$receive['coupon']['createtime']){
                $coupons[$i]['statusTime'] = ['code'=>-1,'msg'=>'未开始'];
            }else if(time()>$receive['coupon']['endtime']){
                $coupons[$i]['statusTime'] = ['code'=>0,'msg'=>'已结束'];
            }else{
                $coupons[$i]['statusTime'] = ['code'=>1,'msg'=>'期间'];
            }
        }
        if($option==1){
            $coupons = array_filter($coupons,function($coupon){
                return $coupon['statusUseable']['code']==1;
            });
        }else if($option==2){
            $coupons = array_filter($coupons,function($coupon){
                return $coupon['statusUseable']['code']==0;
            });
        }else if($option==3){
            $coupons = array_filter($coupons,function($coupon){
                return $coupon['statusTime']['code']==-1;
            });
        }else if($option==4){
            $coupons = array_filter($coupons,function($coupon){
                return $coupon['statusUseable']['code']==0;
            });
        }
        // halt($coupons);
        return $coupons;
    }
}